import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 计数器的使用
 */
public class CountDownLatchDemo1 {
    public static void main(String[] args) throws InterruptedException {
        //创建计数器
        CountDownLatch countDownLatch=new CountDownLatch(5);
        ExecutorService service= Executors.newFixedThreadPool(5);
        //创建线程执行任务
        for (int i = 1; i <6 ; i++) {
            service.submit(()->{
                Thread currThread=Thread.currentThread();
                System.out.println(currThread.getName()+"开始起跑");
                //跑步所用时间
                int runTime=(1+new Random().nextInt(5));
                try {
                    TimeUnit.SECONDS.sleep(runTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(currThread.getName()+"到达终点,用时："+runTime);
                countDownLatch.countDown();
            });
        }
        //阻塞等待，直到所有线程执行结束
        countDownLatch.await();
        System.out.println("比赛结果的宣布");
    }
}
